<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <h3>基础信息</h3>
      </el-row>
      <el-form-item label="商品类目" prop="channelList">
        <el-cascader
          v-model="channelList"
          :options="channelTree"
          :props="{label:'name',value:'id' }"
          @change="handleChannelChange"></el-cascader>
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品名称" :autofocus="true" />
      </el-form-item>
      <el-form-item label="商城价" prop="defaultprice">
        <el-input type="number" v-model="form.defaultprice" placeholder="请输入商城销售价" />
      </el-form-item>
      <el-form-item label="市场价" prop="marketprice">
        <el-input type="number" v-model="form.marketprice" placeholder="请输入市场销售价" />
      </el-form-item>
      <el-row>
        <h3>商品规格</h3>
      </el-row>
      <el-form-item label="是否有规格" prop="haveSku">
        <el-radio-group v-model="form.haveSku" @change="handelHaveSkuChange">
          <el-radio :label="-1">无规格</el-radio>
          <el-radio :label="1">常规规格</el-radio>
          <el-radio :label="2">多规格</el-radio>
        </el-radio-group>
<!--        <el-switch-->
<!--          v-model="form.haveSku"-->
<!--          inactive-text="常规规格"-->
<!--          active-text="多规格"-->
<!--          inactive-value="1"-->
<!--          active-value="2"-->
<!--        >-->
<!--        </el-switch>-->
      </el-form-item>
      <el-row v-if="form.haveSku===2" style="margin-left: 120px;margin-bottom: 30px">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleAddAttribute"
        >添加规格</el-button>
      </el-row>
      <el-form-item
        v-for="(attribute, index) in form.attributeList"
        :label="'规格' + (index+1)"
        :key="attribute.key"
        :rules="{ required: true, message: '商品规格不能为空', trigger: 'blur' }"
      >
        <el-row>
          <el-select placeholder="请选择商品规格类目" v-model="attribute.attributeParentId" @change="handleSelectAttributeParent(attribute,index)">
            <el-option
              v-for="item in attributeParentList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-button type="danger" @click="removeAttributeParent(index)" style="margin-left: 30px">删除</el-button>
        </el-row>

        <el-checkbox-group v-model="attribute.checkAttribute" @change="buildSkuTable" v-show="form.attributeList[index].childrenList && form.attributeList[index].childrenList.length>0">
          <el-checkbox v-for="children in attribute.childrenList" :label="children.name" :key="children.id">{{children.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-row v-show="skuTableList && skuTableList.length>0">
        <el-col :span="6">
          <el-form-item label="库存数">
            <el-input type="number" v-model="allStore" placeholder="请输入市场销售价" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="销售价">
            <el-input type="number" v-model="allPrice" placeholder="请输入市场销售价" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="setAllStoreAndPrice" style="margin-left: 30px">一键填充</el-button>
        </el-col>
      </el-row>
      <el-table :data="skuTableList" border v-show="skuTableList && skuTableList.length>0" style="margin-left: 120px;margin-bottom: 30px;width: 80%">
        <el-table-column label="规格名称" align="center" prop="skunames"/>
        <el-table-column label="库存数" align="center" width="300" prop="store" >
          <template slot-scope="scope">
            <el-input v-model="scope.row.store" placeholder="请输入规格库存数" />
          </template>
        </el-table-column>
        <el-table-column label="销售价" align="center" prop="price" width="300" >
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" placeholder="请输入规格库存数" />
          </template>
        </el-table-column>
      </el-table>


      <el-row>
        <h3>商品相册</h3>
      </el-row>
      <el-form-item label="商品封面">
        <image-upload v-model="form.defaultimage" :limit="1"/>
      </el-form-item>
      <el-form-item label="商品相册">
        <image-upload v-model="form.goodsImageList" :limit="99"/>
      </el-form-item>

      <el-row>
        <h3>商品介绍</h3>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="参数名称">
            <el-input v-model="paramsname" placeholder="请输入参数名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="参数值">
            <el-input v-model="paramsvalue" placeholder="请输入参数值"/>
          </el-form-item>
        </el-col>
        <el-col :span="6" :push="1">
          <el-button size="small" type="success" @click="addGoodsParam">添加</el-button>
        </el-col>
      </el-row>

        <el-table :data="goodsParamsList" v-if="goodsParamsList && goodsParamsList.length>0" style="margin-left: 120px;margin-bottom: 30px">
          <el-table-column label="参数名称" align="center" prop="paramsname" width="80" />
          <el-table-column label="参数值" align="center" prop="paramsvalue" width="300" />
          <el-table-column label="操作" align="center" width="300" >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="warning"
                icon="el-icon-delete"
                @click="handleDeleteParams(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label="商品描述">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods,auditGoods,changeSellStatus,addNormalGoods } from "@/api/smy/mallGoods";
import { getAllGoodsChannel } from "@/api/smy/goodsChannel";
import { listParentList,getAttributeInfo } from "@/api/smy/goodsAttribute";
import {handleTree} from "../../utils/ruoyi";

export default {
  name: "Goods",
  data() {
    return {
      channelList:[],
      channelTree:[],
      goodsParamsList:[],
      attributeParentList:[],
      skuTableList:[],
      paramsname:'',
      paramsvalue:'',
      allStore:'',
      allPrice:'',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      imageUrlList:[],
      // 表单参数
      form: {
        goodsParamsList:[],
        attributeList:[],


      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        defaultprice: [
          { required: true, message: "平台销售价不能为空", trigger: "blur" }
        ],
        marketprice: [
          { required: true, message: "市场销售价不能为空", trigger: "blur" }
        ],
        defaultimage: [
          { required: true, message: "商品封面不能为空", trigger: "blur" }
        ],
        goodsImageList: [
          { required: true, message: "商品相册不能为空", trigger: "blur" }
        ],
        salesvolume: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        postage: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        postagetype: [
          { required: true, message: "$comment不能为空", trigger: "change" }
        ],
        havesku: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        gram: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        bargainprice: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        bargainstore: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        marketingtype: [
          { required: true, message: "$comment不能为空", trigger: "change" }
        ],
        bargainstatus: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        bargainsalesvolume: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        seckillprice: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        seckillsalesvolume: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        seckillstatus: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        seckillstore: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        presellprice: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        presellsalesvolume: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        presellstatus: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        groupbookingcondition: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        groupbookinglimit: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        groupbookingprice: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        groupbookingsalesvolume: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        groupbookingstatus: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        groupbookingtotal: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        groupbookingstore: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        issupplier: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        affiliatedunitvalue: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        havemultiunit: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        ultimateunitvalue: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        supplierpostage: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        supplierpostagetype: [
          { required: true, message: "$comment不能为空", trigger: "change" }
        ],
        recommendsupplier: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        isissuingtype: [
          { required: true, message: "$comment不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getGoodsChannelList();
    this.getGoodsAttributeList();
  },
  methods: {
    getGoodsChannelList(){
      getAllGoodsChannel().then(response => {
        const channelList = response.data || [];
        let channelTree = handleTree(channelList,"id","parent");
        this.channelTree = channelTree;
      });
    },
    getGoodsAttributeList(){
      listParentList().then(response=>{
        this.attributeParentList = response.rows || [];
      })
    },
    setAllStoreAndPrice(){
      let skuTableList = [];
      if(this.allStore && this.allPrice && this.skuTableList.length>0){
        this.skuTableList.forEach(item=>{
          skuTableList.push({
            ...item,
            store:this.allStore,
            price:this.allPrice,
          })
        })
      }
      this.skuTableList = skuTableList;
    },
    handelHaveSkuChange(){
      let skuTableList = [];
      if(this.form.haveSku===1){
        skuTableList.push({
          skuno:2,
          skunames:'常规',
          store:0,
          price:0,
        })
      }
      this.allPrice='';
      this.allStore='';
      this.skuTableList = skuTableList;
    },
    handleSelectAttributeParent(attribute,index){
      // let parentId = opt;
      // console.log(attribute);
      // console.log(index);
      const selectParentId  = attribute.attributeParentId;
      if(selectParentId){
        getAttributeInfo(selectParentId).then(resp=>{
          const childrenList = resp.data.goodsAttributeList || [];
          let attributeList = [];
          for(let i=0;i< this.form.attributeList.length;i++){
            if(i===index){
              if(childrenList.length>0){
                attributeList.push({...this.form.attributeList[i],childrenList:childrenList});
              }else{
                attributeList.push({...this.form.attributeList[i],childrenList:[]});
              }
            }else{
              attributeList.push({...this.form.attributeList[i]});
            }
          }
          this.form.attributeList = attributeList;
        })
      }
    },
    removeAttributeParent(index){
      let attributeList = [];
      for(let i=0;i< this.form.attributeList.length;i++){
        if(i!==index){
          attributeList.push({...this.form.attributeList[i]});
        }
      }
      this.form.attributeList = attributeList;
      this.buildSkuTable();
    },
    buildSkuTable(){
      const attributeList = this.form.attributeList || [];
      let skuTableList = [];
      for(let i=0;i<attributeList.length;i++){
        // console.log(JSON.stringify(skuTableList));
        const attributeItem = attributeList[i];
        const childrenList = attributeItem.childrenList;
        const checkAttribute = attributeItem.checkAttribute;
        let checkItem = [];
        let skuList = [];
        // console.log(JSON.stringify(checkAttribute));
        for(let j=0;j<checkAttribute.length;j++){
          let attributeName = checkAttribute[j];
          // console.log(JSON.stringify(attributeName));
          childrenList.forEach(item=>{
            if(item.name===attributeName){
              checkItem.push(item);
            }
          })
        }
        // console.log(JSON.stringify(checkItem));

        if(skuTableList.length>0){
          if(checkItem.length>0){
            skuTableList.forEach(leftItem=>{
              checkItem.forEach(rightItem=>{
                skuList.push({
                  skunames:leftItem.skunames+","+rightItem.name,
                  skuno:leftItem.skuno+"-"+rightItem.id,
                  store:0,
                  price:0,
                })
              })
            })
          }
        }
        if(skuTableList.length===0){
          if(checkItem.length>0){
            checkItem.forEach(item=>{
              skuList.push({
                skunames:item.name,
                skuno:item.id,
                store:0,
                price:0,
              })
            })
          }
        }
        // console.log(JSON.stringify(skuList));
        if(skuList.length>0){
          skuTableList = skuList;
        }
      }
      this.skuTableList = skuTableList;
    },
    addGoodsParam(){
      let paramList = this.goodsParamsList || [];
      if(this.paramsname && this.paramsvalue){
        paramList.push({
          paramsname:this.paramsname,paramsvalue:this.paramsvalue
        })
        this.paramsname = "";
        this.paramsvalue = "";
        this.goodsParamsList = paramList;
      }
    },
    handleDeleteParams(row){
      let paramList =[];
      if(this.goodsParamsList.length>0){
        paramList = this.goodsParamsList.filter(item=>item !== row);
        console.log(paramList);
      }
      this.goodsParamsList = paramList;
    },
    handleChannelChange(){

    },
    handleAddAttribute(){
      //设置最多5级SKU
      if(this.form.attributeList.length<5){
        this.form.attributeList.push({
          attributeParentId:'',
          checkAttribute:[],
          childrenList:[],
          key: Date.now(),
        })
      }
    },
    // 取消按钮
    cancel() {
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        content: null,
        createtime: null,
        defaultimage: null,
        goodsno: null,
        name: null,
        status: 0,
        goodschannelId: null,
        merchantId: null,
        defaultprice: null,
        marketprice: null,
        qualificationimage: null,
        store: null,
        applytime: null,
        checknote: null,
        checktime: null,
        recommend: null,
        salesvolume: null,
        postage: null,
        postagetype: null,
        havesku: null,
        attributechannelId: null,
        gram: null,
        freighttemplateId: null,
        bargainbegintime: null,
        bargainendtime: null,
        bargainprice: null,
        bargainstore: null,
        marketingtype: null,
        begindateofvalidity: null,
        enddateofvalidity: null,
        bargainstatus: 0,
        bargainsalesvolume: null,
        seckillprice: null,
        seckillsalesvolume: null,
        seckillstatus: 0,
        seckillstore: null,
        seckillsessionId: null,
        presellprice: null,
        presellretainagepaybegintime: null,
        presellretainagepayendtime: null,
        presellsalesvolume: null,
        presellstatus: 0,
        presellsubscriptionpaybegintime: null,
        presellsubscriptionpayendtime: null,
        groupbookingbegintime: null,
        groupbookingcondition: null,
        groupbookingendtime: null,
        groupbookinglimit: null,
        groupbookingprice: null,
        groupbookingsalesvolume: null,
        groupbookingstatus: 0,
        groupbookingtotal: null,
        groupbookingstore: null,
        issupplier: null,
        brandId: null,
        affiliatedunitvalue: null,
        havemultiunit: null,
        ultimateunitvalue: null,
        affiliatedunitId: null,
        ultimateunitId: null,
        unitId: null,
        supplierpostage: null,
        supplierpostagetype: null,
        supplierfreighttemplateId: null,
        recommendsupplier: null,
        isissuingtype: null,
        issuinggoodsId: null,
        recommendtime: null,
        sellstatus: "0",
        rankno: null,
        dishcount: null,
        provideballoon: null,
        providechair: null,
        provideclean: null,
        tableservicenum: null,
        tablemax: null,
        provideinvoice: null,
        nomaterial: null,
        nomaterialprice: null,
        withmaterial: null,
        withmaterialprice: null,
        goodstype: null,
        providebreakfast: null,
        roomtype: null,
        shopcostprice: null
      };
      this.channelList=[];
      this.skuTableList=[];
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm() {
      // console.log(this.skuTableList);
      // console.log(this.form);
      if(this.channelList.length===0){
        this.$modal.msgError("请选择商品类目");
        return false;
      }
      if(this.channelList.length<3){
        this.$modal.msgError("请选择商品类目");
        return false;
      }
      if(!this.form.haveSku){
        this.$modal.msgError("请选择商品规格");
        return false;
      }
      if(this.form.haveSku>0 && this.skuTableList.length===0){
        this.$modal.msgError("请设置商品规格");
        return false;
      }
      this.skuTableList.forEach(item=>{
        if(!item.store || item.store <0){
          this.$modal.msgError("请设置商品库存");
          return false;
        }
        if(!item.price || item.price <0){
          this.$modal.msgError("请设置商品价格");
          return false;
        }
      })
      if(this.form.defaultimage.length===0){
        this.$modal.msgError("请上传商品封面");
        return false;
      }
      let imageUrlList = this.form.goodsImageList || [];
      let goodsImageList = [];
      if(imageUrlList.length>0){
        imageUrlList.forEach(item=>{
          goodsImageList.push({name:item.name})
        })
      }
      if(goodsImageList.length===0){
        this.$modal.msgError("请上传商品图片");
        return false;
      }
      if(this.goodsParamsList.length>0){
        this.goodsParamsList.forEach(param=>{
          if(!param.paramsname || !param.paramsvalue){
            this.$modal.msgError("请填写商品参数");
            return false;
          }
        })
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          let formDate = {
            goodschannelId:this.channelList[2],
            ...this.form,
            goodsSkuList:this.skuTableList,
            goodsParamsList:this.goodsParamsList,
            defaultimage:this.form.defaultimage[0].name,
            goodsImageList,
          };

          if (this.form.id != null) {
            let imageUrlList = this.form.goodsImageList;
            let goodsImageList = [];
            if(imageUrlList.length>0){
              imageUrlList.forEach(item=>{
                goodsImageList.push({name:item.name})
              })
            }
            this.form.goodsImageList = goodsImageList;

          } else {
            addNormalGoods(formDate).then(response=>{
              this.$modal.msgSuccess("新增成功");
              this.reset();
            })
          }
        }
      });
    },
  }
};
</script>
